package com.citicup.backend.service;

import com.citicup.backend.dao.UserMapper;
import com.citicup.backend.entity.User;
import com.citicup.backend.vo.ResponseVO;
import com.citicup.backend.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
public class UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public ResponseVO register(UserVO userVO) {
        if (userMapper.findByUsername(userVO.getUsername()).size() > 0) {
            return ResponseVO.buildFailure("user exist");
        } else if ("".equals(userVO.getUsername()) || "".equals(userVO.getPassword())) {
            return ResponseVO.buildFailure("cannot be null");
        } else {
            User user = new User(userVO.getUsername(), userVO.getPassword());
            userMapper.save(user);
            return ResponseVO.buildSuccess("register successful", user);
        }
    }

    public ResponseVO login(UserVO userVO) {
        List<User> list = userMapper.findByUsernameAndPassword(userVO.getUsername(), userVO.getPassword());
        if (list.size() > 0) {
            assert list.size() == 1;
            System.out.println(list.get(0).getId());
            return ResponseVO.buildSuccess("login successful", list.get(0));
        } else {
            return ResponseVO.buildFailure("user not found");
        }
    }

    public ResponseVO showUser(int id) {
        Optional<User> optionalUser = userMapper.findById(id);
        ResponseVO responseVO;
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            responseVO = ResponseVO.buildSuccess("user found", user);
        } else {
            responseVO = ResponseVO.buildFailure("userID not found");
        }
        return responseVO;
    }

    public ResponseVO survey(UserVO userVO) {
        List<User> optionalUser = userMapper.findByUsername(userVO.getUsername());
        ResponseVO responseVO;
        if (optionalUser.size() == 1) {
            User user = optionalUser.get(0);
            BeanUtils.copyProperties(user, userVO);
            userMapper.save(user);
            responseVO = ResponseVO.buildSuccess("survey successful", user);
        } else {
            responseVO = ResponseVO.buildFailure("userID not found");
        }
        return responseVO;
    }

}
